package com.inet.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.inet.consoleservices.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Utils {

	public static String imei;
	public static boolean isAccOff;
	public static long lastUploadTime;
	private static long UPLOAD_GAP= 1 * 30 * 60 * 1000L;
	@SuppressLint("SimpleDateFormat")
	public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static Map<String, String> properMap = new HashMap<String, String>();

	/**
	 * 获取机器的IMEI
	 * 
	 * @param pContext
	 * @return
	 */
	public static String getImei(Context pContext) {
		if (null == imei || imei.equals("")) {
			imei = ((TelephonyManager) pContext
					.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		}
		return imei;
	}
	
	/**
	 * 获取车机速度
	 * @return
	 */
	public static int getSpeed(){
		return 0;
	}
	
	/**
	 * 判断字符串对象是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {

		if (null == str || "".equalsIgnoreCase(str.trim())) {
			return true;
		} else
			return false;
	}

	/**
	 * 初始化配置文件属性
	 */
	public static void readProperties(Context context) {
		Properties prop = new Properties();
		// 读取属性文件http.properties
		try {
			prop.load(context.getAssets().open("http.properties")); // /加载属性列表
			Iterator<String> it = prop.stringPropertyNames().iterator();
			while (it.hasNext()) {
				String key = it.next();
				properMap.put(key, prop.getProperty(key));
			}
		} catch (FileNotFoundException e) {
			L.i("readProperties FileNotFoundException==" + e.toString());
		} catch (IOException e) {
			L.i("readProperties IOException==" + e.toString());
		}
	}

	/**
	 * 获取对应配置文件的值
	 * 
	 * @param key
	 * @return
	 */
	public static String getPropertiesValue(String key) {
		return properMap.get(key);
	}
	
	/**
	 * 获取版本号
	 * @param context
	 * @return
	 * @throws NameNotFoundException
	 */
	public static  String getVersionName(Context context) throws NameNotFoundException{
		 PackageManager packageManager =context.getPackageManager();
			PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		  return packInfo.versionName;
	}
	
	
	/**
	 * 比较服务器与本地软件的版本号，需要更新则返回true
	 * @param context
	 * @return
	 */
	public static boolean queryVersion(Context context) {
		Map<String, String> versionMap=new HashMap<String, String>();
		versionMap.put("getVersion", "true");
		String resultVersion=HttpUtil.sendGet(versionMap, Utils.getPropertiesValue("post_get_version"));
		try {
			//获得服务器的版本号
			JSONObject versionJson=new JSONObject(resultVersion);
			String newVersion=versionJson.getString("version");
			
			//获得本地的版本号
			String oldVersion=Utils.getVersionName(context);
			if(oldVersion.equals(newVersion)){
				return false;
			}else{
				return true;
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 检验是否存在相关包名的apk
	 * @param context
	 * @param packageName  包名
	 * @return
	 */
	public static boolean checkApkExist(Context context, String packageName) {
	        if (packageName == null || "".equals(packageName)) return false;
	        try {
	            ApplicationInfo info =
	                    context.getPackageManager().getApplicationInfo(packageName,
	                            PackageManager.GET_UNINSTALLED_PACKAGES);
	            return true;
	        } catch (NameNotFoundException e) {
	            return false;
	        }
	    }
	
	
	/**
	 * 通过url获取二维码图片
	 * @param str
	 * @param context
	 * @return
	 * @throws WriterException
	 */
	public static Bitmap Create2DCode(String str, Context context) throws WriterException {
		// BitmapFactory.Options options = new BitmapFactory.Options();
		// options.inJustDecodeBounds = true;
		BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, (int) context.getResources().getDimension(R.dimen.code_width),
				(int) context.getResources().getDimension(R.dimen.code_height));
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = 0xff000000;
				}
			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}
	
	/**
	 * 判断是否超过半个小时， 半个小时之内只上传一张图片
	 * @param wakeLock
	 * @return
	 */
	public static boolean isAboveTime(WakeLock wakeLock) {
		L.i("Utils:isAboveTime---lastUploadTime=" + lastUploadTime);
		if (System.currentTimeMillis() - lastUploadTime > UPLOAD_GAP) {
			lastUploadTime = System.currentTimeMillis();
			return false;
		} else {
			try {
				wakeLock.release();
			} catch (Exception e) {
			}
			return true;
		}
	}
}
